package com.nebula.salary.portal.config.security.component;

import com.nebula.salary.common.constants.Const;
import com.nebula.salary.common.utils.RedisUtil;
import com.nebula.salary.model.pojo.Navigation;
import com.nebula.salary.model.pojo.Role;
import com.nebula.salary.portal.service.INavigationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 权限控制
 * 根据请求url分析请求所需的角色
 *
 * @author codex
 * @since 2022-02-10
 */
@Component
public class CustomFilter implements FilterInvocationSecurityMetadataSource {
    
    @Autowired
    private INavigationService navigationService;
    
    @Autowired
    private RedisUtil redisUtil;
    
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<Navigation> navigations = redisUtil.getObject(Const.MENU_ROLE_KEY + Const.ROLE_SECURITY_PREFIX);
        if (navigations == null || navigations.size() <= 0) {
            navigations = navigationService.getNavigationWithRole();
            redisUtil.setObject(Const.MENU_ROLE_KEY + Const.ROLE_SECURITY_PREFIX, navigations, 30, TimeUnit.DAYS);
        }
        for (Navigation navigation : navigations) {
            // 判断请求url与菜单角色是否匹配
            if (antPathMatcher.match(navigation.getUrl(), requestUrl)) {
                String[] str = navigation.getRoles().stream().map(Role::getRoleSecurity).toArray(String[]::new);
                return SecurityConfig.createList(str);
            }
        }
        return SecurityConfig.createList(Const.ROLE_LOGIN);
    }
    
    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }
    
    @Override
    public boolean supports(Class<?> clazz) {
        return false;
    }
}
